﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Pampa.GenericEntity
{
    public class GenericEntityDataManager
    {
        private readonly string _connStringName;

        public GenericEntityDataManager(string connStringName)
        {
            _connStringName = connStringName;
        }

        public void CreateTables()
        {
            string connString = System.Configuration.ConfigurationManager.ConnectionStrings[_connStringName].ConnectionString;
            var conn = new System.Data.SqlClient.SqlConnection(connString);
            conn.Open();

            var command = new System.Data.SqlClient.SqlCommand("drop table GenericProperty", conn);
            try { command.ExecuteNonQuery(); }
            catch { };

            command = new System.Data.SqlClient.SqlCommand("drop table GenericEntity", conn);
            try { command.ExecuteNonQuery(); }
            catch { };

            command = new System.Data.SqlClient.SqlCommand(@"IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GenericEntity]')) BEGIN
                                                             CREATE TABLE [dbo].[GenericEntity]([ID] [int] IDENTITY(1,1) NOT NULL,[Type] [varchar](50) NULL, [Status] [char](1) NULL)
                                                             END", conn);
            command.ExecuteNonQuery();

            command = new System.Data.SqlClient.SqlCommand(@"IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GenericProperty]')) BEGIN
                                                             CREATE TABLE [dbo].[GenericProperty]([ID] [int] IDENTITY(1,1) NOT NULL,[EntityID] [int] NULL, [ParentID] [int] NULL, [Type] [char](1) NULL, [EntityType] [varchar](255) NULL, [Name] [varchar](50) NULL, [StringValue] [varchar](1024) NULL, [BitValue] bit NULL, [NumericValue] float NULL, [DateTimeValue] datetime NULL)
                                                             END", conn);
            command.ExecuteNonQuery();

            conn.Close();
        }
    }
}
